<template>
    <div id="tree">
   
   <button @click="startTrackLine">开始</button> 
    </div>
</template>

<script>

// import appConfig from "./point.js";
// import CesiumInit from "./index.js";
// import Lgis from "@/js/lgis.js";
    export default {
        data() {
            return {
                defaultchecked: [1],
            //      cluserImages :[],
            //   cluserColors:[],
                data: [
                    {
                        id: 1,
                        label: "轨迹回放",
                        children: []

                    },
                ],
                defaultProps: {
                    children: "children",
                    label: "label",
                },
            };
        },
        created() {
       this.load3dtiles();
       viewer.scene.globe.depthTestAgainstTerrain = true;
        },
        mounted() {
            
        },
        methods: {

  

  initTrackLine() {
        let positions = [
            { x: -1642062.4931434297, y: 5410171.878762089, z: 2942120.265805077 }, { x: -1642225.693936076, y: 5410202.670971577, z: 2941983.2852063235 }, { x: -1642236.5784680916, y: 5410190.49953113, z: 2941997.963186566 }, { x: -1642321.4446279989, y: 5410080.409373888, z: 2942141.4960064585 }
        ]

        this.addTrackLine(positions);
    },

    addTrackLine(positions) {
        this.clearAnimateEntity();
        let timeObj = this.getSiteTimes(positions, 50);
        let startTime = Cesium.JulianDate.fromDate(new Date(2015, 2, 25, 16)); //Cesium.JulianDate.fromDate(new Date());
        let stopTime = Cesium.JulianDate.addSeconds(startTime, timeObj.timeSum, new Cesium.JulianDate());

        viewer.clock.startTime = startTime.clone();
        viewer.clock.stopTime = stopTime.clone();
        viewer.clock.currentTime = startTime.clone();
        viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;

        let hostIPAndPort =VUE_APP_BASE_API;// window.location.origin;// http:192.168.1.61:9527
        let imageURL=hostIPAndPort+'/data/redCar.glb';
        debugger;

        let property = this.computeCirclularFlight(positions, startTime, timeObj.siteTimes);
        this.animateEntity = viewer.entities.add({
            availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                start: startTime,
                stop: stopTime
            })]),
            position: property,
            orientation: new Cesium.VelocityOrientationProperty(property),

            model: {
                // uri: "static/gltf/redCar.glb",
                // uri: "http://localhost/redCar.glb",

                uri:imageURL,

                //  uri: './redCar.glb',
              
                //   uri:JSON.stringify('./redCar.glb') 
                //   uri: "./redCar.glb",
                //   uri:JSON.stringify('blueCamera.png') 
                //  uri:require('./blueCamera.png'), 
                // uri: require('./redCar.glb'),
                 scale: 0.13
            },
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 10
            }
        });

        this.timoutId = setTimeout(e => {
            this.clearAnimateEntity();
        }, timeObj.timeSum * 1000)
    },

    //清除轨迹
    clearAnimateEntity() {
        if (this.animateEntity) {
            viewer.entities.remove(this.animateEntity);
            this.animateEntity = undefined;
        }
        clearTimeout(this.timoutId);
    },


    //获取飞行的动画点位
    computeCirclularFlight(pArr, startTime, siteTimes) {
        var property = new Cesium.SampledPositionProperty();
        for (var i = 0; i < pArr.length; i++) {
            const time = Cesium.JulianDate.addSeconds(startTime, siteTimes[i], new Cesium.JulianDate());
            property.addSample(time, pArr[i]);
        }
        return property;
    },

    //计算每个点位时间与总时间
    getSiteTimes(pArr, speed) {
        let timeSum = 0,
            times = [];
        for (var i = 0; i < pArr.length; i++) {
            if (i == 0) {
                times.push(0); //第0个时间为0
                continue;
            }
            timeSum += this.spaceDistance([pArr[i - 1], pArr[i]]) / speed;
            times.push(timeSum);
        }
        return {
            timeSum: timeSum,
            siteTimes: times
        }
    },

    //计算距离
    spaceDistance(positions) {
        let distance = 0;
        for (let i = 0; i < positions.length - 1; i++) {
            let point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
            let point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
            /**根据经纬度计算出距离**/
            let geodesic = new Cesium.EllipsoidGeodesic();
            geodesic.setEndPoints(point1cartographic, point2cartographic);
            let s = geodesic.surfaceDistance;
            //返回两点之间的距离
            s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
            distance = distance + s;
        }
        return distance.toFixed(2);
    },

    // gps转笛卡尔坐标[[x,y,z],[x,y,z]]
    gpsPointsToCartesian3s(gpsPoints) {
        for (let i = 0; i < gpsPoints.length; i++) {
            const element = gpsPoints[i];
            gpsPoints[i] = Cesium.Cartesian3.fromDegrees(element[0], element[1], element[2])
        }
    },


    //加载3dtiles数据
    load3dtiles() {
        var tileset = viewer.scene.primitives.add(
            new Cesium.Cesium3DTileset({
              url: "http://116.63.83.180:8080/data-01/zy3dtiles/tileset.json",
            })
        );

        tileset.readyPromise
            .then(tileset => {
                viewer.zoomTo(
                    tileset,
                );
                this.setTilesetHeight(tileset);
            })
            .otherwise(function(error) {
                console.log(error);
            });
    },

    //调整3dtiles的高度位置
    setTilesetHeight(tileset) {
        var cartographic = Cesium.Cartographic.fromCartesian(
            tileset.boundingSphere.center
        );
        var surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            cartographic.height
        );
        var offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude, 55
        );
        var translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
        );
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    },


            //    DestroyCluster() {
             
            // }
        
           startTrackLine() {
      this.initTrackLine();
    },
        },
          beforeDestroy() {
 
  },
        destroyed() {
        }
    };
</script>
